package com.zp.datax.core;

import com.zp.datax.core.util.ThreadPoolFactory;
import com.zp.datax.service.DataxJobLogService;
import com.zp.datax.service.DataxJobTriggerService;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

@Component
public class DataxJobProviderFactory implements InitializingBean, DisposableBean {


    @Value("${datax.home}")
    private String dataxHome;
    @Value("${logRetentionDays}")
    private int logRetentionDays;
    @Resource
    private DataxJobTriggerService dataxJobTriggerService;
    @Resource
    private DataxJobLogService dataxJobLogService;
    private DataxJobThread dataxJobThread;


    @Override
    public void destroy() throws Exception {
        this.dataxJobThread.destroy();
        ThreadPoolFactory.INSTANCE.shutdown();
        JobLogFileCleanThread.getInstance().toStop();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.dataxJobThread = new DataxJobThread(dataxJobTriggerService, dataxJobLogService);
        this.dataxJobThread.init();
        JobLogFileCleanThread.getInstance().start(dataxJobLogService, getDataxLogDir(), logRetentionDays);
    }

    public DataxJobThread getDataxJobThread() {
        return this.dataxJobThread;
    }

    public String getDataxHome() {
        return dataxHome;
    }

    public String getDataxLogDir() {
        return String.format(
                "%s%slog"
                , dataxHome
                , File.separator);
    }
}
